package org.gatech.linalg;

import java.io.*;
import java.util.StringTokenizer;

public class MatrixWriter {

	public static void writeGrayscale(Matrix m, String filename, int maxValue)
			throws IOException {
		System.err.println("Printing out WRONG image");
		PrintWriter out = new PrintWriter(filename);
		out.println("P2");
		out.println("# " + new File(filename).getName());
		out.println(m.getCols() + " " + m.getRows());
		out.println(maxValue);
		int x = 0, y = 0, charCount = 0;
		double[][] vals = m.getVals();

		for (int i = 0; i < m.getCols() * m.getRows(); i++) {
			int value = (int) (vals[y][x] + 0.5);
			if (value < 0)
				value = 0;
			if (value > maxValue)
				value = maxValue;
			int spaces = ("" + maxValue).length() - ("" + value).length();
			for (int s = 0; s < spaces; s++)
				out.print(" ");
			out.print(value + " ");
			charCount += ("" + maxValue + " ").length();
			if (charCount > 70 - ("" + maxValue + " ").length()) {
				out.print("\n");
				charCount = 0;
			}
			x++;
			y += x / vals[0].length;
			x = x % vals[0].length;
		}
		out.flush();
		out.close();
	}

	public static void writeRGB(Matrix[] RGB, String filename, int maxValue)
			throws IOException {
		System.err.println("Printing out image");
		PrintWriter out = new PrintWriter(filename);
		out.println("P3");
		out.println("# " + new File(filename).getName());
		out.println(RGB[0].getCols() + " " + RGB[0].getRows());
		out.println(maxValue);
		int x = 0, y = 0, charCount = 0, rgbindex = 0;
		double[][][] vals = new double[3][][];
		vals[0] = RGB[0].getVals();
		vals[1] = RGB[1].getVals();
		vals[2] = RGB[2].getVals();

		out.print(" ");
		for (int i = 0; i < RGB[0].getCols() * RGB[0].getRows() * 3; i++) {

			int value = (int) (vals[rgbindex][y][x] + 0.5);

			if (value < 0)
				value = 0;
			if (value > maxValue)
				value = maxValue;

			int spaces = ("" + maxValue).length() - ("" + value).length();
			for (int s = 0; s < spaces + 1; s++) {
				out.print(" ");
			}
			out.print(value + " ");
			charCount += ("" + maxValue + " ").length() + 1;
			if (charCount > (70 - ((("" + maxValue + " ").length() + 1) * 3))) {
				out.print("\n ");
				charCount = 0;
			}
			rgbindex = (rgbindex + 1) % 3;
			if (rgbindex == 0) {
				x++;
				y += x / vals[0][0].length;
				x = x % vals[0][0].length;
				if (x == 0)
					System.err.println("Progress: " + y + "/" + vals[0].length);
			}
		}
		out.flush();
		out.close();
	}
}
